using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
using C3.Directory.Services;
using CSI.Directory.Core.Model;
using CSI.Directory.Core.Repositories;
using CSI.Directory.Core.Services;
using log4net;

namespace CSI.Directory.Services
{
    public class DirectoryService : ServiceBase, IDirectoryService
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(DirectoryService));

        public DirectoryService(ISessionService sessionService, IUserRepository userRepo, IDirectoryRepository directoryRepository)
            : base(sessionService, userRepo, directoryRepository)
        {
            
        }

        private TransactionResult Notify(string userEmail)
        { 
            var t = new TransactionResult();
            try{
               
                var to = userEmail;
                var body = "Your listing has been approved.";
                var subject = "Your Baisden directory listing.";
                if(string.IsNullOrEmpty(to))
                {
                    to = ConfigurationManager.AppSettings["adminEmail"];
                    body = "A new listing has been added to the directory. Please approve or deny the request at <a href=\"http://onemillionmentors.com/Directory/Manage\"/>www.onemillionmentors.com/Directory/Manage</a>";
                    subject = "New Baisden directory listing.";
                }
                var mail = new MailMessage("bmgAdmin@baisdenlive.com",to,subject,body);
                mail.IsBodyHtml = true;
                var s = new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]);
                s.Send(mail);
                t.Successful = true;
                return t;

            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                t.Successful = false;
                return t;
                
            }

        }

        public IList<Category> GetAllCategories()
        {
            try
            {
                return DirectoryRepository.GetAllCategories();
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Category>();
                
            }
        }

        public IList<County> GetAllCounties()
        {
            try
            {
                return DirectoryRepository.GetAllCounties();
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<County>();

            }
        }

        public IList<Listing> GetListingsByCategory(int id)
        {
            try
            {
                return DirectoryRepository.GetListingsByCategory(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Listing>();

            }
        }

        public Category GetCategoryByName(string name)
        {
            try
            {
                return DirectoryRepository.GetCategoryByName(name);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new Category();

            }
        }
        public Category GetParentCategoryByName(string name)
        {
            try
            {
                return DirectoryRepository.GetParentCategoryByName(name);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new Category();

            }
        }
        public IList<Category> GetSubCategoriesForCategory(int id)
        {
            try
            {
                return DirectoryRepository.GetSubCategoriesForCategory(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Category>();

            }
        }
        //public TransactionResult AddListing(Listing list, IList<ListingCategory> categories)
        //{
        //    var t = new TransactionResult();
        //    try
        //    {
        //        //var cleanCategories = new List<ListingCategory>();
        //        //foreach (var category in categories)
        //        //{
        //        //    if(cleanCategories.Where(c=>c.Category == category.Category).ToList().Count == 0)
        //        //        cleanCategories.Add(category);
        //        //}
        //        //t = DirectoryRepository.AddListing(list, cleanCategories);
        //        //if(t.Successful)
        //        //{
        //        //    t = Notify(null); 
        //        //}
        //        //return t;
                
        //    }
        //    catch (Exception ex)
        //    {

        //        if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
        //        else Log.Error(ex.Message);
        //        return new TransactionResult(){Successful = false, Exception = ex.Message};

        //    }
        //}
        

        //public IList<Listing> GetListingsForManager()
        //{
        //    try
        //    {
        //        return DirectoryRepository.GetListingsForManager();
        //    }
        //    catch (Exception ex)
        //    {

        //        if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
        //        else Log.Error(ex.Message);
        //        return new List<Listing>();

        //    }
        //}

        public TransactionResult AddCategory(string name, int parent, string alias)
        {
            var t = new TransactionResult();
            try
            {
                var category = new Category
                                   {
                                       Name = name,
                                       ParentId = parent,
                                       CreateDate = DateTime.Now,
                                       ModifiedDate = DateTime.Now,
                                       Total = 0,
                                       Image = string.Empty,
                                       Visible = true,
                                       Position = 1,
                                       Description = string.Empty,
                                       Alias = alias

                                   };
                return DirectoryRepository.AddCategory(category);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                t.Exception = ex.Message;
                return t;
            }
        }
        
        public IList<ListingCategory> GetFeaturedListingCategories()
        {
            try
            {
                return DirectoryRepository.GetFeaturedListingCategories();
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<ListingCategory>();

            } 
        }

        public TransactionResult RemoveFeature(ListingCategory listingCategory)
        {
            try
            {
                var l = DirectoryRepository.GetListingCategoryBy(listingCategory.Id);
                if(l == null) return new TransactionResult(){Successful = false,Exception = "Listing category not found."};
                l.Feature = false;
                return DirectoryRepository.RemoveFeature(l);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult();

            } 
        }

        public IList<Listing> GetAllListings()
        {
            try
            {
                return ((IRepositoryBase)DirectoryRepository).GetAll<Listing>();
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Listing>();

            } 
        }

        public IList<Listing> SearchDirectory(string query, int category, int county)
        {
            try
            {
                return DirectoryRepository.SearchDirectory(query, category, county);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Listing>();

            } 
        }

        public IList<Listing> GetFeaturedListings()
        {
            try
            {
                
                return DirectoryRepository.GetFeaturedListings();
               
                 
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Listing>();

            } 
        }

        public Category GetParentCategoryById(int id)
        {
            try
            {
                return ((IRepositoryBase) DirectoryRepository).GetById<Category>(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new Category();

            }
        }

        public TransactionResult AddListing(int userid, string contact, string title, string email, string url, string phone,
            string address, string address2, string city, string state, string zipcode,
            string description, string keywords, string category1, string category2,
            string category3, string category4, string category5, string category6,
            string category7, string category8, string category9, string category10,
            string county1, string county2, string county3, string county4, string county5)
        {
            
            var t = new TransactionResult() {Successful = false};
            try
            {
                var l = DirectoryRepository.GetListingsByUserId(userid);
                if(l.Count > 0)
                {
                    DirectoryRepository.DeleteCategoryAndCountyForListing(l[0].Id);
                    ((IRepositoryBase) DirectoryRepository).Delete(l);
                }
                var file = HttpContext.Current.Request.Files["image"];
                var path = string.Empty;
                if (file != null)
                {
                    try
                    {
                        
                        if (file.ContentLength > 0 &&
                            (file.ContentType == "image/jpeg" || file.ContentType == "image/gif" ||
                             file.ContentType == "image/png"))
                        {
                            var assets = HttpContext.Current.Request.MapPath("/Assets/Images");
                            path = Path.Combine(assets, Path.GetFileName(file.FileName));
                            file.SaveAs(path);
                            path = file.FileName;
                            
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex.Message);
                    }
                }
                if (!string.IsNullOrEmpty(url))
                {
                    if (!url.StartsWith("http://")) url = url.Insert(0, "http://");
                }
                var listing = new Listing()
                                  {
                                      UserId = userid,
                                      Name = title,
                                      AddressLine1 = address,
                                      AddressLine2 = address2,
                                      Contact = contact,
                                      City = city,
                                      State = state,
                                      Zip = zipcode,
                                      Attachment = string.Empty,
                                      CreateDate = DateTime.Now,
                                      ModifiedDate = DateTime.Now,
                                      Description = description,
                                      Email = email,
                                      Image = path,
                                      Keywords = keywords,
                                      Url = HttpContext.Current.Server.HtmlEncode(url),
                                      Phone = phone,
                                      Active = true

                                  };
                if(SessionService.CurrentUser.Package == 3)
                    listing.Featured = true;
                ((IRepositoryBase)DirectoryRepository).Add(listing);

                var categories = new List<ListingCategory>();
                var counties = new List<ListingCounty>();

                if (!string.IsNullOrEmpty(category1) && Int32.Parse(category1) > 0)
                    categories.Add(new ListingCategory() {Category = Int32.Parse(category1),Listing = listing.Id});
                if (!string.IsNullOrEmpty(category2) && Int32.Parse(category2) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category2), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category3) && Int32.Parse(category3) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category3), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category4) && Int32.Parse(category4) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category4), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category5) && Int32.Parse(category5) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category5), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category6) && Int32.Parse(category6) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category6), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category7) && Int32.Parse(category7) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category7), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category8) && Int32.Parse(category8) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category8), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category9) && Int32.Parse(category9) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category9), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category10) && Int32.Parse(category10) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category10), Listing = listing.Id });

                if (county1 != null && Int32.Parse(county1) == -1)
                {
                    var list = DirectoryRepository.GetAllCounties();
                    foreach (var c in list)
                    {
                        counties.Add(new ListingCounty() { County = c.Id, Listing = listing.Id });
                    }
                }
                else
                {

                    if (!string.IsNullOrEmpty(county1) && Int32.Parse(county1) > 0)
                        counties.Add(new ListingCounty() {County = Int32.Parse(county1), Listing = listing.Id});
                    if (!string.IsNullOrEmpty(county2) && Int32.Parse(county2) > 0)
                        counties.Add(new ListingCounty() {County = Int32.Parse(county2), Listing = listing.Id});
                    if (!string.IsNullOrEmpty(county3) && Int32.Parse(county3) > 0)
                        counties.Add(new ListingCounty() {County = Int32.Parse(county3), Listing = listing.Id});
                    if (!string.IsNullOrEmpty(county4) && Int32.Parse(county4) > 0)
                        counties.Add(new ListingCounty() {County = Int32.Parse(county4), Listing = listing.Id});
                    if (!string.IsNullOrEmpty(county5) && Int32.Parse(county5) > 0)
                        counties.Add(new ListingCounty() {County = Int32.Parse(county5), Listing = listing.Id});
                }
                ((IRepositoryBase)DirectoryRepository).AddMany(categories);
                ((IRepositoryBase)DirectoryRepository).AddMany(counties);
                foreach (var c in counties)
                {
                    var county = ((IRepositoryBase) DirectoryRepository).GetById<County>(c.County);
                    county.Total += 1;
                    ((IRepositoryBase) DirectoryRepository).Update(county);
                }

                foreach (var c in categories)
                {
                    var category = ((IRepositoryBase)DirectoryRepository).GetById<Category>(c.Category);
                    category.Total += 1;
                    ((IRepositoryBase)DirectoryRepository).Update(category);
                }
                //update the user in session so they are marked as listed
                SessionService.CurrentUser.IsListed = true;
                t.Successful = true;
                return t;
            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };

            }
        }


        public TransactionResult DeleteCategory(int id)
        {
            var t = new TransactionResult() { Successful = false };
            try
            {
                var category = DirectoryRepository.GetCategoryById(id);
                if(category == null)
                    return t;

                var list = DirectoryRepository.GetSubCategoriesForCategory(category.Id);

                if(list.Count > 0)
                {

                    foreach (var l in list)
                    {
                        var lcs = DirectoryRepository.GetListingCategoryBy(l);
                        foreach (var lc in lcs)
                        {
                            DirectoryRepository.DeleteListingCategory(lc.Id);
                        }
                        DirectoryRepository.DeleteCategory(l.Id);
                    }

                }
                var x = DirectoryRepository.GetListingCategoryBy(category);
                foreach (var lc in x)
                {
                    DirectoryRepository.DeleteListingCategory(lc.Id);
                }
                return DirectoryRepository.DeleteCategory(category.Id);
            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                t.Exception = ex.Message;
                return t;

            }
        }

        public TransactionResult FeatureListing(ListingCategory listingCategory)
        {
            var t = new TransactionResult();
            try
            {
                return DirectoryRepository.FeatureListing(listingCategory);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };

            }
        }
        /*Article Methods Start Here */
        public TransactionResult AddArticle(Article article)
        {
            var t = new TransactionResult();
            try
            {
                return DirectoryRepository.AddArticle(article);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };

            }
        }

        public TransactionResult EditArticle(int id, string name, string body, string menuid, string featured, string desc, string keywords)
        {
            var t = new TransactionResult();
            try
            {
                var article = ((IRepositoryBase)DirectoryRepository).GetById<Article>(id);
                article.Name = name;
                article.Body = body;
                article.MenuId = Convert.ToInt32(menuid);
                article.ModifiedDate = DateTime.Now;
                article.Featured = (featured == "on") ? true : false;
                article.MetaDescription = desc;
                article.MetaKeywords = keywords;
                DirectoryRepository.UpdateArticle(article);
                t.Successful = true;
                return t;

            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };

            }
        }
        public IList<Article> GetArticlesByMenuId(int id)
        {
            try
            {
                return DirectoryRepository.GetArticlesByMenuId(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Article>();

            }
        }

        public TransactionResult AddFreeListing(int userid, string title, string contact, string phone, string category1, string county1)
        {
            var t = new TransactionResult() { Successful = false };
            try
            {
                
                var listing = new Listing()
                {
                    UserId = userid,
                    Name = title,
                    AddressLine1 = null,
                    AddressLine2 = null,
                    Contact = contact,
                    City = null,
                    State = null,
                    Zip = null,
                    Attachment = string.Empty,
                    CreateDate = DateTime.Now,
                    ModifiedDate = DateTime.Now,
                    Description = null,
                    Email = null,
                    Image = null,
                    Keywords = null,
                    Url = null,
                    Phone = phone,
                    Active = true

                };
                ((IRepositoryBase)DirectoryRepository).Add(listing);

                var categories = new List<ListingCategory>();
                var counties = new List<ListingCounty>();

                if (category1 != string.Empty && Int32.Parse(category1) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category1), Listing = listing.Id });
                
                if (county1 != string.Empty && Int32.Parse(county1) > 0)
                    counties.Add(new ListingCounty() { County = Int32.Parse(county1), Listing = listing.Id });
                
                ((IRepositoryBase)DirectoryRepository).AddMany(categories);
                ((IRepositoryBase)DirectoryRepository).AddMany(counties);
                foreach (var c in counties)
                {
                    var county = ((IRepositoryBase)DirectoryRepository).GetById<County>(c.County);
                    county.Total += 1;
                    ((IRepositoryBase)DirectoryRepository).Update(county);
                }

                foreach (var c in categories)
                {
                    var category = ((IRepositoryBase)DirectoryRepository).GetById<Category>(c.Category);
                    category.Total += 1;
                    ((IRepositoryBase)DirectoryRepository).Update(category);

                    
                }

                //update the user in session so they are marked as listed
                SessionService.CurrentUser.IsListed = true;
                t.Successful = true;
                return t;
            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };

            }
        }

        public TransactionResult AddArticle(string name, string body, string menuid, string featured, string desc, string keywords)
        {
            var t = new TransactionResult() {Successful = false};
            try
            {
                var article = new Article()
                                  {
                                      Name = name,
                                      Title = name,
                                      Body = body,
                                      MenuId = Int32.Parse(menuid),
                                      Featured = (featured == "on") ? true : false,
                                      MetaDescription = desc,
                                      MetaKeywords = keywords,
                                      CreateDate = DateTime.Now,
                                      ModifiedDate = DateTime.Now
                                  };
                DirectoryRepository.AddArticle(article);
                t.Successful = true;
                return t;

            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                t.Exception = ex.Message;
                return t;

            }
        }

        public Listing GetListingById(int id)
        {
            try
            {
                return DirectoryRepository.GetListingById(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new Listing();
            }
        }
         
        public TransactionResult EditListing(int id, string contact, string title, string email, string url, string phone, string address, string address2, string city, string state, string zipcode, string description, string keywords)
        {
            var t = new TransactionResult() { Successful = false };
            try
            {
                var file = HttpContext.Current.Request.Files["image"];
                var path = string.Empty;
                if (file != null)
                {
                    if (file.ContentLength > 0 &&
                        (file.ContentType == "image/jpeg" || file.ContentType == "image/gif" ||
                         file.ContentType == "image/png"))
                    {
                        var img = System.Drawing.Image.FromStream(file.InputStream);
                        var assets = HttpContext.Current.Request.MapPath("/Assets/Images");
                        path = Path.Combine(assets, Path.GetFileName(file.FileName));
                        file.SaveAs(path);
                        path = file.FileName;

                    }
                }
                var l = ((IRepositoryBase)DirectoryRepository).GetById<Listing>(id);
                l.Name = title;
                l.Contact = contact;
                l.Email = email;
                l.Description = description;
                l.Url = url;
                if (!string.IsNullOrEmpty(path)) {
                    l.Image = path; }
                l.Phone = phone;
                l.Keywords = keywords;
                l.AddressLine1 = address;
                l.AddressLine2 = address2;
                l.City = city;
                l.State = state;
                l.Zip = zipcode;
                l.ModifiedDate = DateTime.Now;
                t.Successful = true;
                ((IRepositoryBase)DirectoryRepository).Update(l);
                return t;
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                t.Exception = ex.Message;
                return t;
            }
        }

        public IList<Menu> GetMenuByName(string name)
        {
            try
            {
                return DirectoryRepository.GetMenuByName(name);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Menu>();
            }
        }

        public TransactionResult DeleteListing(int id)
        {
            var t = new TransactionResult();
            try
            {
                ((IRepositoryBase) DirectoryRepository).Delete<Listing>(id);
                t.Successful = true;
                return t;

            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                t.Exception = ex.Message;
                return t;
            }
        }

        public IList<ListingCategory> GetListingCategoriesByListingId(int id)
        {
            try
            {
                return DirectoryRepository.GetListingCategoryByListingId(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<ListingCategory>();
            }
        }


        public IList<ListingCounty> GetListingCountiesByListingId(int id)
        {
            try
            {
                return DirectoryRepository.GetListingCountiesByListingId(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<ListingCounty>();
            }
        }

        public TransactionResult EditAssociations(int id, string category0, string category1, string category2,
            string category3, string category4, string category5, string category6,
            string category7, string category8, string category9, string category10,
            string county0, string county1, string county2, string county3, string county4)
        {
            var t = new TransactionResult(){Successful = false};
            try
            {
                var listing = ((IRepositoryBase) DirectoryRepository).GetById<Listing>(id);
                if(listing == null)
                    return t;
                var listingCat = DirectoryRepository.GetListingCategoryByListingId(id);
                var listingCounty = DirectoryRepository.GetListingCountiesByListingId(id);

                foreach (var c in listingCat)
                {
                    var category = ((IRepositoryBase)DirectoryRepository).GetById<Category>(c.Category);
                    category.Total -= 1;
                    ((IRepositoryBase)DirectoryRepository).Update(category);
                    ((IRepositoryBase)DirectoryRepository).Delete<ListingCategory>(c.Id);
                }

                foreach (var c in listingCounty)
                {
                    var county = ((IRepositoryBase)DirectoryRepository).GetById<County>(c.County);
                    county.Total -= 1;
                    ((IRepositoryBase)DirectoryRepository).Update(county);
                    ((IRepositoryBase)DirectoryRepository).Delete<ListingCounty>(c.Id);
                }



                var categories = new List<ListingCategory>();
                var counties = new List<ListingCounty>();

                //if (category0 != null && Int32.Parse(category0) > 0)
                //    categories.Add(new ListingCategory() { Category = Int32.Parse(category0), Listing = listing.Id });
                //if (category1 != null && Int32.Parse(category1) > 0)
                //    categories.Add(new ListingCategory() { Category = Int32.Parse(category1), Listing = listing.Id });
                //if (category2 != null && Int32.Parse(category2) > 0)
                //    categories.Add(new ListingCategory() { Category = Int32.Parse(category2), Listing = listing.Id });
                //if (category3 != null && Int32.Parse(category3) > 0)
                //    categories.Add(new ListingCategory() { Category = Int32.Parse(category3), Listing = listing.Id });
                //if (category4 != null && Int32.Parse(category4) > 0)
                //    categories.Add(new ListingCategory() { Category = Int32.Parse(category4), Listing = listing.Id });

                if (!string.IsNullOrEmpty(category0) && Int32.Parse(category0) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category0), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category1) && Int32.Parse(category1) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category1), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category2) && Int32.Parse(category2) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category2), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category3) && Int32.Parse(category3) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category3), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category4) && Int32.Parse(category4) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category4), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category5) && Int32.Parse(category5) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category5), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category6) && Int32.Parse(category6) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category6), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category7) && Int32.Parse(category7) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category7), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category8) && Int32.Parse(category8) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category8), Listing = listing.Id });
                if (!string.IsNullOrEmpty(category9) && Int32.Parse(category9) > 0)
                    categories.Add(new ListingCategory() { Category = Int32.Parse(category9), Listing = listing.Id });
                

                if (county0 != null && Int32.Parse(county0) == -1)
                {
                    var list = DirectoryRepository.GetAllCounties();
                    foreach (var c in list)
                    {
                        counties.Add(new ListingCounty() { County = c.Id, Listing = listing.Id });
                    }
                }
                else
                {

                    //if (county0 != null && Int32.Parse(county0) > 0)
                    //    counties.Add(new ListingCounty() { County = Int32.Parse(county0), Listing = listing.Id });
                    //if (county1 != null && Int32.Parse(county1) > 0)
                    //    counties.Add(new ListingCounty() { County = Int32.Parse(county1), Listing = listing.Id });
                    //if (county2 != null && Int32.Parse(county2) > 0)
                    //    counties.Add(new ListingCounty() { County = Int32.Parse(county2), Listing = listing.Id });
                    //if (county3 != null && Int32.Parse(county3) > 0)
                    //    counties.Add(new ListingCounty() { County = Int32.Parse(county3), Listing = listing.Id });
                    //if (county4 != null && Int32.Parse(county4) > 0)
                    //    counties.Add(new ListingCounty() { County = Int32.Parse(county4), Listing = listing.Id });

                    if (!string.IsNullOrEmpty(county0) && Int32.Parse(county0) > 0)
                        counties.Add(new ListingCounty() { County = Int32.Parse(county0), Listing = listing.Id });
                    if (!string.IsNullOrEmpty(county1) && Int32.Parse(county1) > 0)
                        counties.Add(new ListingCounty() { County = Int32.Parse(county1), Listing = listing.Id });
                    if (!string.IsNullOrEmpty(county2) && Int32.Parse(county2) > 0)
                        counties.Add(new ListingCounty() { County = Int32.Parse(county2), Listing = listing.Id });
                    if (!string.IsNullOrEmpty(county3) && Int32.Parse(county3) > 0)
                        counties.Add(new ListingCounty() { County = Int32.Parse(county3), Listing = listing.Id });
                    if (!string.IsNullOrEmpty(county4) && Int32.Parse(county4) > 0)
                        counties.Add(new ListingCounty() { County = Int32.Parse(county4), Listing = listing.Id });

                }
                ((IRepositoryBase)DirectoryRepository).AddMany(categories);
                ((IRepositoryBase)DirectoryRepository).AddMany(counties);
                foreach (var c in counties)
                {
                    var county = ((IRepositoryBase)DirectoryRepository).GetById<County>(c.County);
                    county.Total += 1;
                    ((IRepositoryBase)DirectoryRepository).Update(county);
                }

                foreach (var c in categories)
                {
                    var category = ((IRepositoryBase)DirectoryRepository).GetById<Category>(c.Category);
                    category.Total += 1;
                    ((IRepositoryBase)DirectoryRepository).Update(category);
                }
                t.Successful = true;
                return t;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                t.Exception = ex.Message;
                return t;
            }
        }

        public IList<Listing> GetListingsByUserId(int id)
        {
            try
            {
                return DirectoryRepository.GetListingsByUserId(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Listing>();
            }
        }

        public Listing GetListingByUserId(int id)
        {
            try
            {
                return DirectoryRepository.GetListingByUserId(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new Listing();
            }
        }

        public TransactionResult ActivateListingForUser(int id)
        {
            var t = new TransactionResult();
            try
            {
                var l = DirectoryRepository.GetListingByUserId(id);
                l.Active = true;
                ((IRepositoryBase)DirectoryRepository).Update(l);
                t.Successful = true;
                return t;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };

            }
        }

        public County GetCountyByName(string name)
        {
            try
            {

                return DirectoryRepository.GetCountyByName(name);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new County();

            }
        }


        public Article GetArticlesById(int id)
        {
            try
            {
                return DirectoryRepository.GetArticleById(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new Article();
            }
        }

        public TransactionResult DeleteArticle(int id)
        {
            var t = new TransactionResult();
            try
            {
                return DirectoryRepository.DeleteArticle(id);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };
            }
        }
        /* Articles Methods Ends Here*/


        /*Menu Methods Start Here*/
        

        public TransactionResult AddMenu(Menu menu)
        {
            var t = new TransactionResult();
            try
            {
                return DirectoryRepository.AddMenu(menu);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };

            }
        }

        public TransactionResult EditMenu(Menu menu)
        {
            var t = new TransactionResult();
            try
            {
                return DirectoryRepository.UpdateMenu(menu);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };

            }
        }
        public Menu GetMenusById(int id)
        {
            try
            {
                return DirectoryRepository.GetMenusById(id);
            }
            catch (Exception ex)
            {

                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new Menu();

            }
        }

        public IList<Menu> GetAllMenus()
        {
            try
            {
                return DirectoryRepository.GetAllMenus();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new List<Menu>();

            }
        }
        public TransactionResult DeleteMenu(int id)
        {
            var t = new TransactionResult();
            try
            {
                return DirectoryRepository.DeleteMenu(id);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) Log.Error(ex.Message + Environment.NewLine + ex.InnerException);
                else Log.Error(ex.Message);
                return new TransactionResult() { Successful = false, Exception = ex.Message };
            }
        }

        public IList<Listing> GetListingsByCounty(int id)
        {
            try
            {
                return DirectoryRepository.GetListingsByCounty(id);
            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                return new List<Listing>();

            }
        }

        public County GetCountyById(int id)
        {
            try
            {
                return DirectoryRepository.GetCountyById(id);
            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                return new County();

            }
        }

        public IList<Article> GetArticlesForMenuByTitle(string title)
        {
            try
            {
                var menu = DirectoryRepository.GetAllMenus().SingleOrDefault(t => t.Name.ToLower() == title.ToLower());
                if (menu == null) return new List<Article>();
                return DirectoryRepository.GetArticlesByMenuId(menu.Id);
            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                return new List<Article>();

            }
        }

        public IList<Article> GetAllArticles()
        {
            try
            {

                return DirectoryRepository.GetAllArticles();

            }
            catch (Exception ex)
            {

                Log.Error(ex.Message);
                return new List<Article>();

            }
        }


        /*Menu Methods Ends Here*/
         
    }
}